package io.renren.modules.generator.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.modules.generator.dao.CrewInfoDao;
import io.renren.modules.generator.dao.ExperienceInfoDao;
import io.renren.modules.generator.entity.CrewInfoEntity;
import io.renren.modules.generator.entity.ExperienceInfoEntity;
import io.renren.modules.generator.query.CrewInfoQuery;
import io.renren.modules.generator.service.CrewInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Optional;

import static cn.hutool.core.date.DateUtil.ageOfNow;


@Service("crewInfoService")
@Slf4j
public class CrewInfoServiceImpl extends ServiceImpl<CrewInfoDao, CrewInfoEntity> implements CrewInfoService {

    @Autowired
    private CrewInfoDao crewInfoDao;
    @Autowired
    private ExperienceInfoDao experienceInfoDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        CrewInfoQuery ciq = CrewInfoQuery.builder()
                .key(params.get("key") != null ? params.get("key").toString() : null)
                .userId((Long) params.get("userId"))
                .companyId((Long) params.get("companyId"))
                .crewPost(params.get("crewPost") != null ? params.get("crewPost").toString() : null)
                .certificateLevel(params.get("certificateLevel") != null ? params.get("certificateLevel").toString() : null)
                .crewStatus(params.get("crewStatus") != null ? params.get("crewStatus").toString() : null)
                .ageFrom(params.get("ageFrom") != null ? (Long.valueOf((String) params.get("ageFrom"))) : null)
                .ageTo(params.get("ageTo") != null ? (Long.valueOf((String) params.get("ageTo"))) : null)
//                .ageTo((Long) params.get(Integer.valueOf("ageTo")))
                .build();

        IPage<CrewInfoEntity> page = crewInfoDao.selectPage(
                new Query<CrewInfoEntity>().getPage(params),
                new QueryWrapper<CrewInfoEntity>().lambda()
                        //根据每个人的公司id查询，管理员没有绑定公司id
                        .eq(ciq.getCompanyId() != null, CrewInfoEntity::getAffiliatedCompanyId, ciq.getCompanyId())
                        //关键字不为空则加入到sql
                        .and(StringUtils.isNotBlank(ciq.getKey()),
                                //船员姓名
                                i -> i.like(CrewInfoEntity::getCrewName, ciq.getKey())
                                        //证件号
                                        .or().like(CrewInfoEntity::getDocumentNumber, ciq.getKey())
                                        //推荐人
                                        .or().like(CrewInfoEntity::getRecommenderId, ciq.getKey()))
                        .and(StringUtils.isNotBlank(ciq.getCrewPost()),
                                //职务
                                i -> i.eq(CrewInfoEntity::getCrewPost, ciq.getCrewPost()))
                        .and(StringUtils.isNotBlank(ciq.getCertificateLevel()),
                                //证书等级
                                i -> i.eq(CrewInfoEntity::getCertificateLevel, ciq.getCertificateLevel()))
                        .and(StringUtils.isNotBlank(ciq.getCrewStatus()),
                                //状态
                                i -> i.eq(CrewInfoEntity::getCrewStatus, ciq.getCrewStatus()))
                        .and(ciq.getAgeFrom() != null || ciq.getAgeTo() != null,
                                //状态
                                i -> i.between(CrewInfoEntity::getAge, ciq.getAgeFrom(), ciq.getAgeTo()))
                        //倒序创建时间排序
                        .orderByDesc(CrewInfoEntity::getCreateTime)
        );

        page.getRecords().stream().forEach(f -> {
            //计算年龄
            Optional.ofNullable(f.getBirthday()).ifPresent(birthday -> {
                f.setAge(ageOfNow(birthday));
            });
            //查询该船员的履历
            List<ExperienceInfoEntity> experienceList =
                    experienceInfoDao.selectList(
                            new QueryWrapper<ExperienceInfoEntity>().lambda().eq(ExperienceInfoEntity::getCrewId, f.getCrewId()));
            f.setExperience_list(experienceList);

            //修改年龄
            CrewInfoEntity crewInfoEntity = new CrewInfoEntity();
            crewInfoEntity.setCrewId(f.getCrewId());
            crewInfoEntity.setAge(f.getAge());
            this.updateById(crewInfoEntity);
        });
        return new PageUtils(page);
    }
}